﻿/*----------------------------------------------------------------
//  <copyright file="Knife4jBuilderExtensions.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2022-11-15 15:48</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Swagger.Knife4j
{
    #region "Knife4j构建扩展方法"
    /// <summary>
    /// Knife4j构建扩展方法
    /// </summary>
    public static class Knife4jBuilderExtensions
    {
        #region "扩展方法"
        #region "使用Knife4jUI"
        /// <summary>
        /// 使用Knife4jUI
        /// </summary>
        /// <param name="app">应用构建器</param>
        /// <param name="options">Knife4j配置选项</param>
        /// <returns></returns>
        public static IApplicationBuilder UseKnife4jUI(this IApplicationBuilder app, Knife4jOptions options)
        {
            return app.UseMiddleware<Knife4jMiddleware>(options);
        }
        #endregion
        #region "使用Knife4jUI"
        /// <summary>
        /// 使用Knife4jUI
        /// </summary>
        /// <param name="app">应用构建器</param>
        /// <param name="setupAction">Knife4j配置选项活动</param>
        /// <returns></returns>
        public static IApplicationBuilder UseKnife4jUI(this IApplicationBuilder app, Action<Knife4jOptions> setupAction = null)
        {
            var options = new Knife4jOptions();
            using (var scope = app.ApplicationServices.CreateScope())
            {
                options = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<Knife4jOptions>>().Value;
                setupAction?.Invoke(options);
            }

            if (options.ConfigObject.Urls == null)
            {
                var hostingEnv = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
                options.ConfigObject.Urls = new[] { new UrlDescriptor { Name = $"{hostingEnv.ApplicationName} v1", Url = "v1/swagger.json" } };
            }
            return app.UseKnife4jUI(options);
        }
        #endregion

        #endregion

    }
    #endregion

}
